<?php

declare (strict_types=1);

namespace app\shop\controller\order;

use think\response\Json;
use app\shop\controller\Controller;
use app\shop\model\order\Delivery as DeliveryModel;
use app\store\service\order\EOrder as EOrderService;
use app\store\service\order\Delivery as DeliveryService;

/**
 * 订单发货管理
 * Class Delivery
 * @package app\store\controller\order
 */
class Delivery extends Controller
{
    /**
     * 订单发货记录
     * @return Json
     */
    public function list(): Json
    {
        $model = new DeliveryModel;
        $list = $model->getList($this->request->param());
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 发货单详情
     * @param int $deliveryId 发货单ID
     * @return Json
     */
    public function detail(int $deliveryId): Json
    {
        $detail = DeliveryModel::detail($deliveryId);
        return $this->renderSuccess(compact('detail'));
    }

    /**
     * 确认发货 (手动录入)
     * @param int $orderId 订单ID
     * @return Json
     */
    public function delivery(int $orderId): Json
    {
        $service = new DeliveryService;
        if ($service->delivery($orderId, $this->postForm())) {
            return $this->renderSuccess('发货成功');
        }
        return $this->renderError($service->getError() ?: '发货失败');
    }

    /**
     * 批量发货 (导入模板文件)
     * @return Json
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \cores\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function batch(): Json
    {
        $service = new DeliveryService;
        if ($service->batch($this->shopId)) {
            return $this->renderSuccess('批量发货成功');
        }
        return $this->renderError($service->getError() ?: '批量发货失败');
    }

    /**
     * 确认发货 (电子面单)
     * @param int $orderId 订单ID
     * @return Json
     * @throws \cores\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function eorder(int $orderId): Json
    {
        $service = new EOrderService;
        if (!$service->eorder($orderId, $this->postForm())) {
            return $this->renderError($service->getError() ?: '发货失败');
        }
        $template = $service->getEOrderContent();
        return $this->renderSuccess(compact('template'), '发货成功');
    }
}